package com.smartStatus.admin.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.smartStatus.admin.service.SysFileService;
import com.smartStatus.core.util.FileUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName : SysFileServiceImpl
 * @Author : lby
 * @Date: 2021/3/2 17:00
 * @Description :
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysFileServiceImpl implements SysFileService {
    private final FileUtils fileUtils;

    @Override
    public Map<String, String> uploadFile(MultipartFile file) {
        //        文件名称
        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        Map<String, String> map = new HashMap<>();
        map.put("fileName", fileName);
        map.put("bucketName", "images");
        map.put("url", "/admin/sysFile" + String.format("/%s/%s", "images", fileName));
        map.put("originalName", file.getOriginalFilename());
        try {
            fileUtils.uploadFile(file, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return map;
    }

    @SneakyThrows
    @Override
    public void getFile(String bucketName, String fileName, HttpServletResponse response) {
        try (InputStream file = fileUtils.getFile(bucketName, fileName);) {
            response.setContentType("application/octet-stream; charset=UTF-8");
            IoUtil.copy(file, response.getOutputStream());
        } catch (Exception e) {
            log.error("文件读取异常: {}", e.getLocalizedMessage());
        }
    }


    @Override
    public String getImageUrl(String bucketName, String fileName) {
        return fileUtils.getFileUrl(bucketName, fileName);
    }
}
